import json
import xml.etree.ElementTree as xee

from config import RedisNames
from support import redis
from support.decorators import timer
from support.string_process import jd


class GetCoordinates:
    osm = '../doc/doc_map.osm'
    coordinates_file = 'all_coordinates'

    @classmethod
    def run(cls):
        cls.parse_osm()

    @classmethod
    def deal_node(cls, node):
        lat = node.get("lat")
        lon = node.get("lon")
        coordinate = [lat, lon]
        added = redis.sadd(RedisNames.坐标点_去重, jd(coordinate))
        redis.rpush(RedisNames.坐标点nodes, jd(coordinate))
        if added:
            redis.rpush(RedisNames.坐标点, jd(coordinate))
            with open(cls.coordinates_file, 'a', encoding='utf-8') as f:
                f.write(jd(coordinate) + '\n')

    @classmethod
    @timer
    def parse_osm(cls):
        # 读取文件
        domTree = xee.parse(cls.osm)
        # 获得所有节点的内容
        root = domTree.getroot()
        # 获得所有"node"节点列表
        nodes = root.findall("node")
        for node in nodes:
            cls.deal_node(node)
        print(len(nodes))
        print(redis.llen(RedisNames.坐标点))
        print(redis.scard(RedisNames.坐标点_去重))

    @classmethod
    def test(cls):
        坐标点nodes = redis.lrange(RedisNames.坐标点nodes, 0, -1)
        print(len(坐标点nodes))
        print(type(坐标点nodes))
        print(坐标点nodes)
        rows = [json.loads(i.decode()) for i in 坐标点nodes]
        res = []
        for row in rows:
            if row not in res:
                res.append(row)
        print(len(rows))
        print(len(res))


if __name__ == '__main__':
    GetCoordinates.run()
